﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Repository;
using PersonalHealth.Data.Model;
using Core.UnitOfWork;

namespace PersonalHealth.Data.Repository
{
    public class MessageRepository : Repository<Message>, IMessageRepository
    {
        public MessageRepository(IUnitOfWork unitOfWork)
            : base(unitOfWork)
        {
           
        }

        public int GetNotReadMessageCount(int userid)
        {
            return DbSet.Count(c => c.ToUserId == userid && c.NotRead == true);
        }

        public IList<Message> GetUserMessages(int userid, int pageIndex, int pageCount, out int msgCount, out int notReadCount)
        {
            var q = DbSet.Include("FromUser").Include("ToUser").Where(c => c.ToUserId == userid);

            msgCount = q.Count();
            notReadCount = q.Count(c => c.NotRead == true);

            return q.OrderByDescending(c => c.CreateDate).Skip((pageIndex - 1) * pageCount).Take(pageCount).ToList();
        }

        public IList<Message> GetUserMessages(int userid, MessageType type, int pageIndex, int pageCount, out int msgCount, out int notReadCount)
        {
            var q = DbSet.Include("FromUser").Include("ToUser").Where(c => c.ToUserId == userid);

            if (type == MessageType.System)
            {
                q = q.Where(c => c.MsgTypeId == (int)MessageType.System);
                msgCount = q.Count();
                notReadCount = q.Count(c => c.NotRead == true);
                return q.OrderByDescending(c => c.CreateDate).Skip((pageIndex - 1) * pageCount).Take(pageCount).ToList();
            }

            if (type == MessageType.Doctor)
            {
                q = q.Where(c => c.MsgTypeId == (int)MessageType.Doctor);
                msgCount = q.Count();
                notReadCount = q.Count(c => c.NotRead == true);
                return q.OrderByDescending(c => c.CreateDate).Skip((pageIndex - 1) * pageCount).Take(pageCount).ToList();
            }

            throw new ArgumentException("error MessageType!");
        }
    }
}
